package com.ly.imgtooss.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @author ly
 */
public class UploadUtil {
    // 阿里域名
    public static final String ALI_DOMAIN = "";
    // 地域节点
    public static final String ENDPOINT = "";
    // 仓库名
    public static final String BUCKET_NAME = "";
    // 密钥ID
    public static final String ACCESS_KEY_ID = "";
    // 密钥密码
    public static final String ACCESS_KEY_SECRET = "";

    /**
     * 文件上传至阿里云
     * @param file
     * @return
     * @throws IOException
     */
    public static String uploadImage(MultipartFile file) throws IOException {
        // 生成文件名
        String originalFilename = file.getOriginalFilename();
        String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String fileName = uuid + extName;
        // OSS 客户端对象 （地域节点，密钥ID，密钥密码）
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        ossClient.putObject(
                // 仓库名
                BUCKET_NAME,
                // 文件名
                fileName,
                // 文件流
                file.getInputStream()
        );
        ossClient.shutdown();
        return ALI_DOMAIN + fileName;
    }
}
